import requests
import os
import pandas as pd

headers = {
    # 'Accept': 'application/json, text/plain, */*',
    # 'Accept-Language': 'zh-CN,zh;q=0.9',
    # 'Connection': 'keep-alive',
    # 'Content-Type': 'application/json',
    # 'Origin': 'https://www.tianyancha.com',
    # 'Referer': 'https://www.tianyancha.com/',
    # 'Sec-Fetch-Dest': 'empty',
    # 'Sec-Fetch-Mode': 'cors',
    # 'Sec-Fetch-Site': 'same-site',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36',
    # 'X-AUTH-TOKEN': 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxNTE4MjU2MjQ2MiIsImlhdCI6MTc1MDg0NDkyMywiZXhwIjoxNzUzNDM2OTIzfQ.i12htEO6zizLrNdgfyq2lo-2I_NUgQFdnHcm1SVp9Fc-fujmzHBrnYxj6fgj0oG4xlao5mxfR8zaWAXrZvRd8g',
    # 'X-TYCID': 'cce083c04dc411f0acb86d37de551163',
    # 'sec-ch-ua': '"Google Chrome";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
    # 'sec-ch-ua-mobile': '?0',
    # 'sec-ch-ua-platform': '"Windows"',
}

def get_zhuanli(url,s_code):
    
    invent_auth_count = 0
    utility_model_count = 0
    exterior_design = 0
    all_number = 0
    for i in range(2022,2026):

        params = {
        '_': '1750845678454',
        'id': url,
        'pageNum': '1',
        'pageSize': '10',
        'history': '0',
        'type': '-100',
        'lprs': '专利授权',
        'applyYear': i,
        'pubYear': '-100',
        'fullSearchText': '',
        'sortField': '',
        'sortType': '-100',
        }
        response = requests.get(
            'https://capi.tianyancha.com/cloud-intellectual-property/patent/patentListV7',
            params=params,
            headers=headers,
        )
        data = response.json()

        for x in data['data']['type_lmbx'][1:]:
            if '发明授权' in x['key']:
                invent_auth_count += x['itemCount']
            elif '实用新型' in x['key']:
                utility_model_count += x['itemCount']
            elif '外观设计' in x['key']:
                exterior_design += x['itemCount']
        all_number = invent_auth_count+utility_model_count+exterior_design
        # break
    return [[invent_auth_count,utility_model_count,exterior_design,all_number,s_code]]
                

def get_rj(url,s_code):

    number_rj = 0


    for i in range(2022,2026):

        params = {
        '_': '1750920308489',
        'id': '3192738948',
        'pageSize': '10',
        'pageNum': '1',
        'regYear': i,
        'fullSearchText': '',
        }
        response = requests.get(
        'https://capi.tianyancha.com/cloud-intellectual-property/intellectualProperty/softwareCopyrightListV2',
        params=params,
        headers=headers,
        )
        data = response.json()
        # print(data)
        try:
            number_rj += data['data']['regYearLmbx'][1]['itemCount']
            print(number_rj)
        except:
            continue
        
    
    return [[number_rj,s_code]]


    


def write_zhuanli(items):

    file_exists = os.path.exists('./invebt_number_zhunali_sky.csv')
    df = pd.DataFrame(
        items, columns=['发明授权', '实用新型', '外观设计', '总和', '社会信用统一代码'])
    df.to_csv('invebt_number_zhunali_sky.csv', mode='a',
              index=False, header=not file_exists)
    if not file_exists:
        print("创建新文件并写入表头和数据")
    else:
        print("专利信息数据已追加到 invebt_number_zhunali_sky.csv")


def write_rj(items):

    file_exists = os.path.exists('./invebt_number_rj_sky.csv')
    df = pd.DataFrame(
        items, columns=['软件数量', '社会信用统一代码'])
    df.to_csv('invebt_number_rj_sky.csv', mode='a',
              index=False, header=not file_exists)
    if not file_exists:
        print("创建新文件并写入表头和数据")
    else:
        print("软件著作权数据已追加到 invebt_number_rj_sky.csv")


def main():

    with open('./企知道获取的信用代码.txt', 'r', encoding='utf-8') as f:
        s_codes = [s_code.strip() for s_code in f.readlines()]
    with open("./output2.txt", "r", encoding="utf-8") as file:
        urls = [url.strip() for url in file.readlines()]
    for url,s_code in zip(urls,s_codes):

        data_zhaunli = get_zhuanli(url,s_code)
        data_rj = [[0,s_code]]

        # print(data_zhaunli)
        # data_rj = get_rj(url,s_code)
        # if data_rj :
        #     pass
        # else:
        #     data_rj = [[0,s_code]]
        write_zhuanli(data_zhaunli)
        write_rj(data_rj)
        # print(data_rj)
        # break


if __name__ == "__main__":
    main()